package io.sage.common.rxtx;

import com.alibaba.fastjson.JSONObject;
import gnu.io.CommPortIdentifier;
import io.sage.modules.rxtx.entity.RfidNotifyData;
import io.sage.modules.rxtx.service.RxtxService;
import org.springframework.stereotype.Component;
import uhf.AsyncSocketState;
import uhf.MultiLableCallBack;
import uhf.Reader;
import uhf.Types;

import javax.annotation.Resource;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by Administrator on 2019/6/4 0004.
 */
@Component
public class RxtxConfig implements MultiLableCallBack {

    private Reader ReaderControllor =  new Reader(this);;//读取对象--初始化串口jar包
    private Enumeration<CommPortIdentifier> portList;//当前可用的串口
    private ArrayList<String> portNameList;//当前可用的串口
    private AsyncSocketState currentclient;    //当前操作客户端对象
    private List<AsyncSocketState> asyncSocketStates; //客户端集合

    private String[] resultData = null;//查询出的数据

    private String lanwifi = "WiFi模块参数";
    private String lanWorkMode = "工作模式";
    private String lanGpio = "GPIO状态";
    private String lanInfo = "网络参数设置";
    private String lanMacAndDev = "MAC地址和设备号";
    private String lan4G = "4G模块参数";
    private String lanFactory = "恢复出厂设置";
    private String lanCommandTest1 = "主板相关指令测试";
    private String lanCommandTest2 = "模块相关指令测试";
    private String lanCommandTest3 = "有源相关指令测试";
    private String lanEPCAndTID = "同时读取EPC和TID";
    private String lanPower = "功率";
    private String lanFRequency = "射频输出频率";
    private String lanGen2 = "Gen2参数";
    private String lanArea = "频率区域";
    private String lanTem = "温度";
    private String lanReadWrite = "标签读，写，锁，销毁";
    private String lanWorkAnt = "天线工作时间和间隔";
    private String lanFastID = "fastID功能";
    private String lanTagfocus = "Tagfocus";
    private String lanQT = "QT标签";
    private String lanInit = "参数初始化";
    private String lanMQTT = "MQTT";
    private String lanBeep = "蜂鸣器设置";
    private String lanCarrier = "载波测试";
    private String lanActivityCarrier = "有源读写器载波测试";
    private String lanFliter = "过滤设置";
    private String lanCommonTestOne = "通用测试一";
    private String lanUHFTest = "超高频测试";
    private String lanCommonTestTwo = "通用测试二";
    private String lanUHFTestTwo = "超高频测试二";
    private String lanUHFTestThree = "超高频测试三";
    private String lanActiveTest = "2.4G测试";
    private String ModuleVersion_9200 = "9200模块版本";
    private String BatchTagAction = "批量写标读标";
    private String HEART = "心跳";

    public List<AsyncSocketState> getAsyncSocketStates() {
        return asyncSocketStates;
    }

    public void setCurrentclient(AsyncSocketState currentclient) {
        this.currentclient = currentclient;
    }

    public String[] getResultData() {
        return resultData;
    }

    //硬件返回的数据
    @Override
    public void method(String data) {

        String flag = "0";

        //划分字符串
        String[] result = (data + "," + flag).split("\\,");
        byte type = toBytes(result[1])[0];
        switch(type)
        {
            case Types.START_MULTI_EPC_RESPOND:
            case Types.START_SINGLE_EPC_RESPOND:
                resultData = result;
                UpDateTags(result);
                break;
            case Types.GET_MULTI_ID:                  //2.4G
                UpdateMultiID(result);
                break;
            case Types.STOP_MULTI_EPC_RESPOND:
                UpdateSetParameters(result, "Mulit Tags");
                break;
            case Types.GET_POWER_RESPOND:
                UpDatePower(result);
                break;
            case Types.SET_POWER_RESPOND:
                UpdateSetParameters(result, lanPower);
                break;
            case Types.GET_COMMUNICATION_INFO_RESPOND:
                UpDateCommunicationInfo(result, lanInfo);
                break;
            case Types.SET_COMMUNICATION_INFO_RESPOND:
                UpdateSetParameters(result, lanInfo);
                break;
            case Types.GET_SIM_RESPOND:
                UpDateSIMInfo(result,lan4G);
                break;
            case Types.SET_SIM_RESPOND:
                UpdateSetParameters(result, "4G");
                break;
            case Types.GET_WIFI_RESPOND:
                UpDateWifiConfig(result,lanwifi);
                break;
            case Types.SET_WIFI_RESPOND:
                UpdateSetParameters(result, "wifi");
                break;
            case Types.GET_MQTT_RESPOND:
                UpDateMQTTUser(result);
                break;
            case Types.SET_MQTT_RESPOND:
                UpdateSetParameters(result, "MQTT");
                break;
            case Types.GET_MQTT_THEME_RESPOND:
                UpDateMQTTTheme(result);
                break;
            case Types.SET_MQTT_THEME_RESPOND:
                UpdateSetParameters(result, "MQTT Theme");
                break;
            case Types.GET_MAC_ADD_RESPOND:
                UpdateLBM(result);
                break;
            case Types.GET_FREQUENCY_AREA_RESPOND:
                UpdateFrequencyArea(result);
                break;
            case Types.GET_WORK_INTERRUPTED_RESPOND:
                UpdateWorkInterrupted(result);
                break;
            case Types.SET_WORK_ANT_RESPOND:
                UpdateSetParameters(result, "WorkAnt");
                break;
            case Types.GET_WORK_ANT_RESPOND:
                UpdateWorkAnt(result);
                break;
            case Types.GET_WORK_TIME_RESPOND:
                UpdateWorkTime(result);
                break;
            case Types.SET_WORK_TIME_RESPOND:
                UpdateSetParameters(result, "WorkTime");
                break;
            case Types.GET_FASTID_RESPOND:
                UpdateFastID(result);
                break;
            case Types.SET_FASTID_RESPOND:
                UpdateSetParameters(result, "FastID");
                break;
            case Types.GET_TAGFOCUS_RESPOND:
                UpdateTagfocus(result);
                break;
            case Types.SET_TAGFOCUS_RESPOND:
                UpdateSetParameters(result, "Tagfocus");
                break;
            case Types.SET_CARRIER_RESPOND:
                UpdateSetParameters(result, "Carrier");
                break;
            case Types.GET_TEMPERATURE_RESPOND:
                UpdateTemperature(result);
                break;
            case Types.GET_EAT_RESPOND:
                UpdateEAT(result);
                break;
            case Types.SET_EAT_RESPOND:
                UpdateSetParameters(result, "EPCAndTID");
                break;
            case Types.GET_RF_LINK_RESPOND:
                UpdateRFLinkl(result);
                break;
            case Types.READ_TAGS_RESPOND:
                UpdateReadTags(result);
                break;
            case Types.WRITE_TAGS_RESPOND:
                UpdateSetParameters(result,"Write Tags");
                break;
            case Types.LOCK_TAGS_RESPOND:
                UpdateSetParameters(result,"Lock Tags");
                break;
            case Types.KILL_TAGS_RESPOND:
                UpdateSetParameters(result,"Kill Tags");
                break;
            case Types.GET_WORK_MODE_RESPOND:
                UpDateWorkMode(result);
                break;
            default:
                break;
        }
    }

    //获取com口
    public List<String> GetCom() {
        //获得当前所有可用串口
        portList = CommPortIdentifier.getPortIdentifiers();
        portNameList = new ArrayList<>();
        //将可用串口名添加到List并返回该List
        while (portList.hasMoreElements()) {
            String portName = portList.nextElement().getName();
            portNameList.add(portName);
        }
        return portNameList;
    }

    //获取电脑Ip地址
    public List<String> getLocalIPList() {
        List<String> ipList = new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddresses;
            InetAddress inetAddress;
            String ip;
            while (networkInterfaces.hasMoreElements()) {
                networkInterface = networkInterfaces.nextElement();
                inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();
                    if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                        ip = inetAddress.getHostAddress();
                        ipList.add(ip);
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ipList;
    }

    //打开或关闭ip服务
    public boolean ipServerAction(boolean isOpen,String serverIp,int serverPort){
        if(isOpen){//打开
            return ReaderControllor.ServerStart(serverIp, serverPort);
        }else{
            return ReaderControllor.ServerClose();
        }
    }

    //打开或关闭com口服务
    public boolean comServerAction(boolean isOpen,String comName,int port){

        if(isOpen){//打开
            return ReaderControllor.ComStart(comName, 115200);
        }else{
            return ReaderControllor.SerialPortClose();
        }
    }


    //获取客户端信息
    public List<AsyncSocketState> getClientInfo() {
        asyncSocketStates = ReaderControllor.GetClientInfo();
        return asyncSocketStates;
    }

    //开启无源RFID扫描
    public boolean StartMultiEPC(){
        String s = ReaderControllor.StartMultiEPC(currentclient);
        System.out.println("--扫描返回结果--");
        return s.equals(epcType.success.getCode());
    }

    //停止无源RFID扫描
    public boolean StopMultiEPC(){
        String s = ReaderControllor.StopMultiEPC(currentclient);
        return s.equals(epcType.success.getCode());
    }


    //将16进制字符串转换为byte[]
    public static byte[] toBytes(String str) {
        if(str == null || str.trim().equals("")) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for(int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }
        return bytes;
    }

    //显示读标数据
//    public void UpDateTags(String[] result) {
//        System.out.println("--获取到数据-,该处可进行数据保存-");
//        try {
//            String Device = PrivateStringFormat.GetDevice(result[0]);
//            String message = "Ant:"+result[4]+"\r\n"+"EPC:"+result[5]+"\r\n"
//                    +"PC:"+result[6]+"\r\n"+"RSSI:"+result[7]+"\r\n"+"DevID:"+Device+"\r\n"
//                    +"ReadTime:"+result[12]+"\r\n"+"Dir:"+result[9]+"\r\n"+"TID:"+result[13];
//            WebSocketServer.sendInfo(message,null);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
    @Resource
    private RxtxService rxtxService;
    //操作读标数据
    public void UpDateTags(String[] result) {
        System.out.println("--获取到数据-,该处可进行数据保存-");
        String Device = PrivateStringFormat.GetDevice(result[0]);
        RfidNotifyData rfidNotifyData = new RfidNotifyData();
        rfidNotifyData.setAnt(result[4]);//(天线号)
        rfidNotifyData.setEpc(result[5]);//(标签EPC)
        rfidNotifyData.setPc(result[6]);//(EPC长度)
        rfidNotifyData.setRssi(result[7]);//(场强)
        rfidNotifyData.setXdTime(result[8]);//(相对时间)
        rfidNotifyData.setDir(result[9]);//(方向)
        rfidNotifyData.setClientIp(result[10]);//(通信IP,串口下为串口号)
        rfidNotifyData.setCount(result[11]);//(读取次数,总是为1,不可当做标签读取次数)
        rfidNotifyData.setReadTime(result[12]);//(本次读取时间)
        rfidNotifyData.setTid(result[13]);
        System.err.println("rfid监测出的数据："+ JSONObject.toJSONString(rfidNotifyData));
        rxtxService.lableDataHandle(result[5]);

    }

    public void UpdateSetParameters(String[] result, String type) {

    }

    public void UpdateMultiID(String[] result) {

    }


    public void UpDateWorkMode(String[] result) {

    }


    public void UpDatePower(String[] result) {

    }

    public void UpDateCommunicationInfo(String[] result,String type) {
    }


    public void UpDateSIMInfo(String[] result,String type) {

    }


    public void UpDateWifiConfig(String[] result,String type) {

    }


    public void UpDateMQTTUser(String[] result) {

    }

    public void UpDateMQTTTheme(String[] result) {

    }

    public void UpdateLBM(String[] result) {

    }

    public void UpdateFrequencyArea(String[] result) {

    }

    public void UpdateWorkInterrupted(String[] result) {

    }


    public void UpdateWorkAnt(String[] result) {

    }

    public void UpdateWorkTime(String[] result) {

    }

    public void UpdateFastID(String[] result) {

    }


    public void UpdateTagfocus(String[] result) {

    }

    public void UpdateTemperature(String[] result) {

    }

    public void UpdateEAT(String[] result) {

    }

    public void UpdateRFLinkl(String[] result) {

    }

    public void UpdateReadTags(String[] result) {

    }

    //读取无源rfid结果的类型
    enum epcType{
        success("0"),
        failure("-4");

        private String code;
        epcType(String type){
            this.code = code;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }
    }
}
